package com.iotimc.attendancesystem.manage.person;

import android.text.TextUtils;
import android.util.Log;

import com.iotimc.attendancesystem.dao.AttendanceLogEntityDao;
import com.iotimc.attendancesystem.dao.DoorLogEntityDao;
import com.iotimc.attendancesystem.dao.GreenDaoManager;
import com.iotimc.attendancesystem.dao.PersonEntityDao;
import com.iotimc.attendancesystem.datautil.ImageData;
import com.iotimc.attendancesystem.entity.PersonEntity;
import com.iotimc.attendancesystem.util.TtsUtil;
import com.pefis.natives.Ast2600JNI;
import com.pefis.natives.PfsBioInfo;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author david
 * @date 2017/12/6
 */

public class PersonPresenter implements PersonContract.Presenter {
    private static final String TAG = "PersonPresenter";
    PersonContract.DeleteView deleteViewView;
    PersonContract.InsertOrUpdateView insertOrUpdateView;
    PersonEntityDao personEntityDao;

    public PersonPresenter(PersonContract.DeleteView view) {
        this.deleteViewView = view;
        personEntityDao = GreenDaoManager.getInstance().getSession().getPersonEntityDao();
    }

    @Override
    public void setInsertOrUpdateView(PersonContract.InsertOrUpdateView insertOrUpdateView) {
        this.insertOrUpdateView = insertOrUpdateView;
    }

    @Override
    public void deletePerson(PersonEntity personEntity) {
        Integer id = personEntity.getICodeId();
        if (id != null) {
            deleteFace(id);
        }
        GreenDaoManager.getInstance().getSession().getPersonEntityDao().delete(personEntity);
        AttendanceLogEntityDao dao = GreenDaoManager.getInstance().getSession().getAttendanceLogEntityDao();
        dao.deleteInTx(dao.queryBuilder().where(AttendanceLogEntityDao.Properties.PersonId
                .eq(personEntity.getId())).list());
        DoorLogEntityDao doorLogEntityDao = GreenDaoManager.getInstance().getSession().getDoorLogEntityDao();
        doorLogEntityDao.deleteInTx(doorLogEntityDao.queryBuilder().where(DoorLogEntityDao.Properties
                .PersonId.eq(personEntity.getId())).list());
        deleteViewView.deleteSuccess();
    }

    @Override
    public void deletePersons(List<PersonEntity> entities) {
        AttendanceLogEntityDao dao =
                GreenDaoManager.getInstance().getSession().getAttendanceLogEntityDao();
        DoorLogEntityDao doorLogEntityDao = GreenDaoManager.getInstance().getSession().getDoorLogEntityDao();
        for (PersonEntity personEntity : entities) {
            Integer id = personEntity.getICodeId();
            if (id != null) {
                deleteFace(id);
            }
            dao.queryBuilder().where(
                    AttendanceLogEntityDao.Properties.PersonId.eq(personEntity.getId())).buildDelete().
                    executeDeleteWithoutDetachingEntities();

            doorLogEntityDao.queryBuilder().where(DoorLogEntityDao.Properties.PersonId.eq(personEntity.getId())).buildDelete().
                    executeDeleteWithoutDetachingEntities();
        }

        GreenDaoManager.getInstance().getSession().getPersonEntityDao().deleteInTx(entities);
        deleteViewView.deleteSuccess();
    }


    public void deleteFace(int id) {
        int errorCode;
        File mDeleteUserData;
        errorCode = Ast2600JNI.getInstance().pisFcDeleteAtTptArray(
                PfsBioInfo.getInstance().mContextID, id);
        if (errorCode == 0) {
            mDeleteUserData = new File(PfsBioInfo.TEMPLATE_DB_PATH + id);
            if (mDeleteUserData.exists()) {
                mDeleteUserData.delete();
            }

            mDeleteUserData = new File(PfsBioInfo.PHOTO_DB_PATH + id + ".JPEG");
            if (mDeleteUserData.exists()) {
                mDeleteUserData.delete();
            }
        }
    }

    @Override
    public boolean checkCardRepeat(String personCard, String newCard) {
        personCard = personCard == null ? "" : personCard;
        if (!TextUtils.isEmpty(newCard) && !personCard.equals(newCard)) {
            PersonEntity cardEntity = personEntityDao.queryBuilder().where(
                    PersonEntityDao.Properties.Card.eq(newCard)).build().unique();
            if (cardEntity != null) {
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean checkCodeRepeat(String personCode, String newCode) {
        if (!personCode.equals(newCode)) {
            PersonEntity codeEntity = personEntityDao.queryBuilder().where(PersonEntityDao.Properties.Code.eq(newCode)).build().unique();
            if (codeEntity != null) {
                return false;
            }
        }
        return true;
    }


    @Override
    public void insertOrUpdate(PersonEntity personEntity, byte[] mHeadByte, boolean admin,
                               String code, String name, String position, String card, String sex) {
        if (personEntity == null) {
            personEntity = new PersonEntity();
            personEntity.setId(UUID.randomUUID().toString().replace("-", ""));
            personEntity.setCreateTime(new Date());
            personEntity.setICodeId(0);
        }

        personEntity.setCode(code);
        personEntity.setAdmin(admin);
        personEntity.setName(name);
        personEntity.setSex(sex);
        personEntity.setCard(card);
        personEntity.setPosition(position);
        personEntity.setUpdateTime(new Date());

        Log.i(TAG, "checkHeadImage: personEntity.getICodeId()" + personEntity.getICodeId());
        if (mHeadByte != null && !checkHeadImage(personEntity, mHeadByte)) {
            return;
        }
        personEntityDao.insertOrReplace(personEntity);
        insertOrUpdateView.insertOrUpdateSuccess();
    }

    private boolean checkHeadImage(PersonEntity personEntity, byte[] mHeadByte) {
        int iCodeId;
        Log.i(TAG, "checkHeadImage: personEntity.getICodeId()" + personEntity.getICodeId());
        if (personEntity.getICodeId() != 0) {
            iCodeId = personEntity.getICodeId();
        } else {
            String columnName = PersonEntityDao.Properties.ICodeId.columnName;
            //查找人脸最后的id
            List<PersonEntity> personImageEntities = personEntityDao.
                    queryRaw(" where " + columnName + " = (select max(" + columnName + ") " +
                            "from " + PersonEntityDao.TABLENAME + ")");

            if (null == personImageEntities || personImageEntities.size() == 0) {
                iCodeId = 1;
            } else {
                iCodeId = (personImageEntities.get(0).getICodeId() + 1);
            }
        }
        PfsBioInfo.getInstance().mEnrollID = iCodeId;
        Log.i(TAG, "保存文件 ID = " + PfsBioInfo.getInstance().mEnrollID);
        int[] dup_id = new int[1];
        Ast2600JNI
                .getInstance()
                .pisFcInfraredLedControl(
                        PfsBioInfo.getInstance().mContextID,
                        PfsBioInfo.PFSBIO_IR_LED_LOW_ON);

        int vnRet = Ast2600JNI
                .getInstance()
                .pisFcCheckDuplicate(
                        PfsBioInfo.getInstance().mContextID,
                        ImageData.getTemplate(), dup_id);
        Log.i(TAG, PfsBioInfo.getInstance().mEnrollID + "   检测重复建模  返回特征码ID:" + dup_id[0] + "返回结果  " + vnRet);
        //
        if (dup_id[0] != PfsBioInfo.getInstance().mEnrollID) {
            if (vnRet != PfsBioInfo.PFSBIO_OK) {
                insertOrUpdateView.insertOrUpdateError("该人脸已经存在!");
                TtsUtil.ttsSpeek2("该人脸已经存在!");
                return false;
            }
        }

        vnRet = Ast2600JNI
                .getInstance()
                .pisFcSetAtTptArray(
                        PfsBioInfo.getInstance().mContextID,
                        PfsBioInfo.getInstance().mEnrollID,
                        ImageData.getTemplate());
        if (vnRet != 0) {
            //设置模型失败
            insertOrUpdateView.insertOrUpdateError("设置模型失败");
            TtsUtil.ttsSpeek2("设置模型失败!");
            return false;
        }
        if (mHeadByte != null) {
            personEntity.setImage(mHeadByte);
        }
        personEntity.setICodeId(iCodeId);
        personEntity.setImageCode(ImageData.getTemplate());

        return true;
    }

}
